<?php

namespace App\Http\Controllers\Data;

use App\library\juhe\Weather;
use Illuminate\Http\Request;
use DB;

use App\Http\Controllers\Controller;

/**
 * 参数接口-获取全部参数
 */
class AreasController extends DataController{

    public function __construct(){
        parent::__construct();
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            return $this->areas($request);
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    public function areas(Request $request){
        // app端保存的缓存数据版本
        $request_version = $request->input('version');

        $data_version = DB::table('data_version')->where('name','areas')->first();
        $version = ($data_version->updated_at)?$data_version->updated_at:$data_version->created_at;

        app()->configure('areas');
        if ($version == config('areas.version')) {
            // 如果版本与服务器版本相同则不返还数据
            if ($request_version == $version) {
                return $this->json('1','当前版本与服务器版本相同');
            }else{
                $data = config('areas');
            }
        }else{
            // 若服务器版本与数据库版本不同，不论app什么版本都直接更新

            $data_areas = DB::table('data_areas')->get();
            // var_dump($data_areas);
            $are_list = array();
            foreach ($data_areas as $area) {
                $area = (array)$area;
                if ($area['is_valid']) {
                    unset($area['is_valid']);
                    unset($area['created_at']);
                    unset($area['updated_at']);
                    $are_list[$area['city']][] = $area;
                }
            }
            $data['version'] = $version;
            $data['content'] = $are_list;

            // 写入到data
            ob_start();
            var_export($data);
            $con = ob_get_contents();
            ob_end_clean();
            $config_dir = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/config/';
            $content = '<?php '.PHP_EOL.'return '.$con.PHP_EOL.';';
            file_put_contents($config_dir.'areas.php', $content);
        }
        return $this->json('1','',$data);
    }
}
